#coding=utf-8
import urllib, urllib2, random
from google.appengine.ext import db,webapp

def is_online(num):
  url = 'http://wpa.qq.com/pa?p=1:%s:1'%num
  f = urllib.urlopen(url)
  url2 = f.geturl()
  if url2.find('online') != -1:
    return True
  else: 
    return False

def get_onlined_qq(a, b):
  while True:
    n = str(random.randint(a,b))
    logging.info(n)
    r = is_online(n)
    if r:
      return n
      
'''
r = re.compile(r'".+":.+,')
r.findall(data)
r = re.compile(r'"(.+)":(.+),')
ds = r.findall(data)
ds[0]
ds
r = re.compile(r'"(.+)":"(.+)",')
r.findall(data)
r = re.compile(r'"(.+)":(\d+),')
r.findall(data)
'''

class QQ(db.Model):
  code = db.StringProperty(required=True)
  flag = db.BooleanProperty(default=False)   
  created_at = db.DateTimeProperty(auto_now_add=True)
      
class GetOnlinedQQ(webapp.RequestHandler):
  def get(self):
    n = get_onlined_qq(50000000,500000000)
    QQ(code=n).put()
    self.response.out.write(n)

class ReceiveOnlinedQQ(webapp.RequestHandler):
  def post(self):
    n = self.request.get('qq')
    QQ(code=n).put()

